﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Data;
using TSL_Tools.SqlTools;
using ReportingEngine;
using System.IO;

namespace VSLT_Reporting
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        /// <summary>
        /// This method searches the datagrid and finds the highlighted run(s). It then
        /// updates various settings based on the runs and the configuration of the app.
        /// It is called from both the "Get Runs" button and the "SelectionChanged" event
        /// handler.
        /// </summary>
        private void GetDatabaseInformation()
        {
            //Sql_GETDATABASEINFO
            string sqlConn = Properties.Settings.Default.sqlConn;
            string sqlCmd = String.Format(TSL_ReportingEngine.Sql_GETDATABASEINFO, Properties.Settings.Default.LoadTestDatabaseName);
            DataSet dataSet;
            tts.ExecuterReaderMultiTable(sqlCmd, out dataSet);
            mostRecentSqlQuery = sqlCmd;
            BuildDatabaseInfoDisplayString(dataSet
                , Properties.Settings.Default.DatabaseInfoTemplateLocation
                , Properties.Settings.Default.DatabaseFileInfoLineTemplateLocation
                , BuildTopTablesDisplayString(Properties.Settings.Default.DatabaseInfoTopTablesTemplateLocation));
            defaultReportName = String.Format(Msg__FILENAMEFORDBINFO, Properties.Settings.Default.LoadTestDatabaseName);
        }

        private void BuildListOfHighlightedRuns(RunsToRetrieve _runs)
        {
            string startDate = "";
            string endDate = "";
            string methodUsed = "";

            if (_runs == RunsToRetrieve.TodayOnly)
            {
                // Nothing selected so get runs for today
                startDate = DateTime.Now.ToShortDateString() + " 00:00:00";
                endDate = DateTime.Now.AddDays(1).ToShortDateString() + " 00:00:00";
                methodUsed = "all runs from today";
            }
            else if (_runs == RunsToRetrieve.SelectedDay)
            {
                // One item selected, so get all runs for the given date
                startDate = re.listOfRuns[currentlyHighlightedRunId].startTime.ToShortDateString() + " 00:00:00";
                endDate = re.listOfRuns[currentlyHighlightedRunId].startTime.ToShortDateString() + " 23:59:59";
                //startDate = lvTestRuns.SelectedItems[0].SubItems[2].Text.Substring(0, 10) + " 00:00:00";
                //endDate = lvTestRuns.SelectedItems[0].SubItems[2].Text.Substring(0, 10) + " 23:59:59";
                methodUsed = "all runs from the day: " + startDate;
            }
            else if (_runs == RunsToRetrieve.SelectedRange)
            {
                // More than one item selected so get all runs between the outermost two dates
                List<string> selectedDates = new List<string>();

                //foreach (ListViewItem item in lvTestRuns.SelectedItems)
                //{
                //    selectedDates.Add(item.SubItems[2].Text);
                //}
                //if (!SortTheDates(selectedDates, ref startDate, ref endDate))
                //{
                //    MessageBox.Show("Sorting the dates failed for some reason. Before you say it, I know. This is a lame message. I have a note to add better error handling here soon.");
                //    return;
                //}
            }
            else if (_runs == RunsToRetrieve.SelectedRuns)
            {

            }

            string sqlCmd = String.Format(TSL_ReportingEngine.Sql_DAILYSTATUSRUNLIST, startDate, endDate);
            string sqlConn = Properties.Settings.Default.sqlConn;
            DataTable _table;
            TimeSpan ts = tts.ExecuteReaderTable(sqlCmd, out _table);
            AddDebugTimingInfo(ts, "--PopulateDataGridWithRuns  " + sqlCmd);
            mostRecentSqlQuery = sqlCmd;
            dgMainResults.ItemsSource = _table.AsDataView();
            tsslMessage.Content = String.Format(Msg_NUMBEROFRESULTSLOADED, _table.Rows.Count);
            re.GetAllCoreLoadTestInfo();
            ClearReportTab();

        }

        private void BuildListOfFilteredRuns()
        {
            string columnName = cbNameFilter.SelectionBoxItem.ToString();
            string adjective = cbComparisonAdjective.SelectionBoxItem.ToString();
            string comparitor = tbComparisonPhrase.Text;

            string sqlCmd = String.Format(TSL_ReportingEngine.Sql_GETFILTEREDRUNLIST, columnName, adjective, comparitor);
            string sqlConn = Properties.Settings.Default.sqlConn;
            DataTable _table;
            TimeSpan ts = tts.ExecuteReaderTable(sqlCmd, out _table);
            AddDebugTimingInfo(ts, "--PopulateDataGridWithRuns  " + sqlCmd);
            mostRecentSqlQuery = sqlCmd;
            dgMainResults.ItemsSource = _table.AsDataView();
            tsslMessage.Content = String.Format(Msg_NUMBEROFRESULTSLOADED, _table.Rows.Count);
            re.GetAllCoreLoadTestInfo();
            ClearReportTab();
        }

        private void GetRunInfoForHighlightedRun(int runId)
        {
            using (StreamReader sr = new StreamReader("Templates\\RunOverviewTemplate.xaml"))
            {
                string str = sr.ReadToEnd();

                bool bUsePerfmon = (bool)cbUsePerfmonForScorecard.IsChecked;
                Dictionary<string, string> timings = re.GetSummaryTimingResultsForReport(runId, bUsePerfmon);

                str = re.listOfRuns[runId].UpdateMainReportStringWithValues(str, timings);

                System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
                MemoryStream ms = new MemoryStream(encoding.GetBytes(str));

                TextRange text = new TextRange(rtbResults.Document.ContentStart, rtbResults.Document.ContentEnd);
                text.Load(ms, DataFormats.Xaml);

                //AddQuickTextToReport(re.listOfRuns[runId].GetprocessingTimesAsString());

                tsslMessage.Content = String.Format("Showing details for run {0}", runId);
            }
        }

        private void showLoadTestForHighlightedRun()
        {
            int x = selectedRuns.Max();
            GetLoadTestInfoForHighlightedRun(x);
            defaultReportName = String.Format(Msg__FILENAMEFORLOADTESTSETTINGS, re.listOfRuns[currentlyHighlightedRunId].LoadTestName, currentlyHighlightedRunId);
        }

        private void ShowAnalysisNotes()
        {
            TextRange text = new TextRange(rtbResults.Document.ContentStart, rtbResults.Document.ContentEnd);
            text.Text = re.listOfRuns[currentlyHighlightedRunId].analysisNotes;
        }

        private void GetLoadTestInfoForHighlightedRun(int runId)
        {
            GetLoadTestInfoForHighlightedRun(runId, false);
        }

    }
}



